<?php
session_start();

header("Content-type:text/html;Charset=utf-8");
//first find root  不用查找 在DEFINE里面已经定义根目录
define('DIR_ROOT_P',dirname(dirname(__FILE__)));
include_once(DIR_ROOT_P.'/../include/fooee.class.mysql.php');
include(DIR_ROOT_P.'/../config.php');
include_once(DIR_ROOT_P.'/../include/functions.php');
//初始化mysql类
$db = new db();
$db -> connect($_DB);
if($_SESSION['sid']==''){
    fs_showmsg('请先登录!');
}
$courseware_id = $_GET['courseware_id'];
$query = "select * from nettteach_courseware where id=".$courseware_id;
$result = $db->query($query);
$courseware_info =$db->fetch_array($result);
$d = download('../../teacher'.$courseware_info['address']);
/*
 * @下载函数
 * @param:file_dir 文件所在目录
 * $param:file_name 文件名
 */
function download($file_path)
{    
    //判断要下载的文件是否存在
    $file_name = basename($file_path);//print_r($file_path);exit();
    if(!file_exists($file_path))
    {
//        echo "<script>alert('对不起,你要下载的文件不存在')</script>";
       exit("<script type='text/javascript'>alert('对不起,你要下载的文件不存在');history.go(-1);</script>");
        return false;
    }
    $file_size = filesize($file_path);

    header("content-type: application/octet-stream");
    header("accept-ranges: bytes");
    header("accept-length: $file_size");
    header("content-disposition: attachment; filename=".$file_name);
    
    $fp = fopen($file_path,"r");
    $buffer_size = 1024;
    $cur_pos = 0;
    
    while(!feof($fp)&&$file_size-$cur_pos>$buffer_size)
    {
        $buffer = fread($fp,$buffer_size);
        echo $buffer;
        $cur_pos += $buffer_size;
    }
    
    $buffer = fread($fp,$file_size-$cur_pos);
   
    fclose($fp);
    return true;
}
if($d){//添加文档下载记录
    $insert_sql  = "insert into nettteach_record (`uid`,`cid`,`datetime`,`type`) values(".$_SESSION['sid'].",".$courseware_info['id'].",".time().",2)";
    $db->query($insert_sql);
    $update_times = "update nettteach_courseware set times = times+1 where id =".$courseware_id;
    $db->query($update_times);
    
}
?>
